import { useEffect } from "react";
import { useHttp } from "./http";
import { cleanObj } from "./index";
import { Project } from "types/project";
import { useAsync } from "./useAsync";
export const useProject = (param?: Partial<Project>) => {
  const client = useHttp();
  const { run, ...state } = useAsync<Project[]>();
  const fetchProjects = () =>
    client("projects", { data: cleanObj(param || {}) });
  useEffect(() => {
    run(fetchProjects(), { retry: fetchProjects });
  }, [param]);
  return state;
};

export const useEditProject = () => {
  const { run, ...asyncResult } = useAsync();
  const client = useHttp();
  const mutite = (params: Partial<Project>) => {
    return run(
      client(`projects/${params.id}`, {
        data: params,
        method: "PATCH",
      })
    );
  };
  return {
    mutite,
    ...asyncResult,
  };
};

export const useAddProject = () => {
  const { run, ...asyncResult } = useAsync();
  const client = useHttp();
  const mutite = (params: Partial<Project>) => {
    return run(
      client(`projects/${params.id}`, {
        data: params,
        method: "POST",
      })
    );
  };
  return {
    mutite,
    ...asyncResult,
  };
};
